package com.example.coordinartordemo.demo1;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;

public class SampleTitleBehavior extends CoordinatorLayout.Behavior  {
    private static final String TAG = "SampleTitleBehavior";
    private float deltaY;

    public SampleTitleBehavior() {
        super();
    }

    public SampleTitleBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 是否给应用了behavior的view指定一个依赖的布局。
     * @param parent
     * @param child 应用behavior的view
     * @param dependency 被依赖的view
     * @return
     */
    @Override
    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        return dependency instanceof RecyclerView;
    }

    /**
     * 被依赖的view发生变化时，调用
     * @param parent
     * @param child
     * @param dependency
     * @return
     */
    @Override
    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        if (deltaY == 0){
            deltaY = dependency.getY() - child.getHeight();
        }
        Log.e(TAG,dependency.getY()+"");
        float dy = dependency.getY() - child.getHeight();
        dy = dy < 0 ? 0 : dy;

        //平移
//        float y = -(dy / deltaY) * child.getHeight();
//        child.setTranslationY(y);

        //透明度
        float alpha = 1 - (dy / deltaY);
        child.setAlpha(alpha);
        return true;
    }
}
